package com.cqut.forum.controller;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.log4j.Logger;
import org.directwebremoting.annotations.RemoteMethod;
import org.directwebremoting.annotations.RemoteProxy;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.cqut.forum.entity.Comment;
import com.cqut.forum.entity.Hotpost;
import com.cqut.forum.entity.Message;
import com.cqut.forum.entity.Post;
import com.cqut.forum.entity.User;
import com.cqut.forum.service.ICommentService;
import com.cqut.forum.service.IMessageService;
import com.cqut.forum.service.IPostService;
import com.cqut.forum.service.IUserService;
import com.cqut.forum.util.ConfigProperties;
import com.cqut.forum.util.CookieHandler;
import com.cqut.forum.util.DESUtils;
import com.cqut.forum.util.DateUtil;
import com.cqut.forum.util.DefaultElements;
import com.cqut.forum.util.StringUtil;

@Controller
@RemoteProxy(name = "postRemoting")  
public class PostController {
	 Logger logger  =  Logger.getLogger(PostController. class );
	private IPostService  postService;
	private ICommentService commentService;
	private IUserService userService;
	private IMessageService messageService; 


	public void setPostService(IPostService postService) {
		this.postService = postService;
	}

	public void setCommentService(ICommentService commentService) {
		this.commentService = commentService;
	}

	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

	public void setMessageService(IMessageService messageService) {
		this.messageService = messageService;
	}

	/**
	* @Title: postDetail
	* @Description:   返回帖子详细信息页面
	* @return String  
	* @author 刘强   
	* @date 2015-5-6 下午2:11:03
	*/ 
	@RequestMapping(value="/postdetail.do")
	public String postDetail(HttpServletRequest request,HttpServletResponse response){
        String postId=request.getParameter("id");
        Post post=postService.getPostById(Long.parseLong(postId));
        post.setPageView(post.getPageView()+1);
        postService.saveOrupdate(post);
		List<Hotpost> hotposts_0 =postService.getHotPostByType(DefaultElements.ZERO, DefaultElements.SIX);
		List<Post> hotposts_1 =postService.getPostByHotpost(DefaultElements.ONE, DefaultElements.TEN);
		User user=userService.getUserById(post.getUserId());
		
		request.setAttribute("post", post);		
		request.setAttribute("user", user);
		request.setAttribute("hotposts_0", hotposts_0);
		request.setAttribute("hotposts_1", hotposts_1);	
		return "home/postdetail";
	}
	/**
	* @Title: postJson
	* @Description: 用于异步加载帖子评论 
	* @return void  
	* @author 刘强   
	* @date 2015-5-6 下午2:10:57
	*/ 
	@RequestMapping(value="/postJson.do")
	public void postJson(HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> root=new HashMap<String,Object>();
		String postId=request.getParameter("postId");
		String page=request.getParameter("page");
		int pageSize=Integer.parseInt(ConfigProperties.get("commentRowNumber"));
		List<Comment> comments=commentService.getComment(Long.parseLong(postId), Integer.parseInt(page), pageSize);
        for(Comment comment:comments){//获取评论
        	User user=userService.get(User.class, comment.getUserId());
        	comment.setUser(user);
        	List<Comment> comms=commentService.getComment(Long.parseLong(postId), comment.getId());
        	for(Comment comm:comms){//获取评论的回复
        		User commUser=userService.get(User.class, comm.getUserId());
        		comm.setUser(commUser);
        		User commTUser=userService.get(User.class, comm.getTuserId());
        		comm.setTuser(commTUser);
        	}
        	comment.setLists(comms);
        }		
		int total=commentService.getCommentTotal(Long.parseLong(postId));
		int rowCount=0;
		if(total%pageSize!=0){
			rowCount = total / pageSize + 1; 
		}else{
			rowCount = total / pageSize; 
		}	
		root.put("pageCount", rowCount);
		root.put("CurrentPage", page);
		root.put("list", comments);
		StringUtil.writeToWeb(JSONObject.fromObject(root).toString(), "html", response);

	}
	/**
	* @Title: postComment
	* @Description: 帖子评论  
	* @return void  
	* @author 刘强   
	* @date 2015-5-6 下午2:10:34
	*/ 
	@RequestMapping(value="/postComment.do")
	public void postComment(HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> root=new HashMap<String,Object>();
		String postId=request.getParameter("postId");
		String content=request.getParameter("content");
		Comment comment=new Comment();
		String cookieValue=DESUtils.decode(CookieHandler.getCookieValue(request, DefaultElements.COOKIE_NAME));
		User user=userService.getUserByEmail(cookieValue);
		comment.setPostId(Long.parseLong(postId));
		comment.setTargetId((long)0);
		comment.setUserId(user.getId());
		comment.setContent(content);
		comment.setDate(DateUtil.getCurrentTimestamp());
		commentService.save(comment);
		//添加帖子评论消息
		Post post=postService.getPostById(Long.parseLong(postId));
		if(post.getUserId()!=user.getId()){
			Message message=new Message();
			message.setUserId(post.getUserId());
			message.setContent(post.getName()+DefaultElements.UPDATE);
			message.setCreateDate(DateUtil.getCurrentTimestamp());
			message.setTargetId(post.getId());
			messageService.saveMessage(message);
		}
		root.put("result", 1);
		StringUtil.writeToWeb(JSONObject.fromObject(root).toString(), "html", response);

	}
	/**
	* @Title: replyJson
	* @Description: 帖子回复  
	* @return void  
	* @author 刘强   
	* @date 2015-5-6 下午2:44:13
	*/ 
	@RequestMapping(value="/replyJson.do")
	public void replyJson(HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> root=new HashMap<String,Object>();
		String tuserid=request.getParameter("tuserid");
		String commentid=request.getParameter("commentid");
		String content=request.getParameter("content");
		Post post=commentService.getPostByCommentId(Long.parseLong(commentid));
		String cookieValue=DESUtils.decode(CookieHandler.getCookieValue(request, DefaultElements.COOKIE_NAME));
		User user=userService.getUserByEmail(cookieValue);
		Comment comment=new Comment();
		comment.setPostId(post.getId());
		comment.setUserId(user.getId());
		comment.setTargetId(Long.parseLong(commentid));
		comment.setContent(content);
		comment.setDate(DateUtil.getCurrentTimestamp());
		comment.setTuserId(Long.parseLong(tuserid));
		commentService.save(comment);
		//添加帖子回复消息
		if(Long.parseLong(tuserid)!=user.getId()){
			Message message=new Message();
			message.setUserId(Long.parseLong(tuserid));
			message.setContent(post.getName()+DefaultElements.REPLY);
			message.setCreateDate(DateUtil.getCurrentTimestamp());
			message.setTargetId(post.getId());
			messageService.saveMessage(message);
		}
		root.put("result", 1);
		StringUtil.writeToWeb(JSONObject.fromObject(root).toString(), "html", response);

	}
	/**
	* @Title: getPersonalPost
	* @Description: TODO  
	* @return void  
	* @author 刘强   
	* @date 2015-5-12 下午2:41:27
	*/ 
	@RequestMapping(value="getPersonalPostJson.do")
	public void getPersonalPostJson(HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> root=new HashMap<String,Object>();
		String page=request.getParameter("page");//当前页
		String cookieValue=DESUtils.decode(CookieHandler.getCookieValue(request, DefaultElements.COOKIE_NAME));
		User user=userService.getUserByEmail(cookieValue);//获取当前用户
		int pageSize=Integer.parseInt(ConfigProperties.get("personPostPageSize"));
		List<Post> posts=postService.getPostByPlateId(user.getId(), Integer.parseInt(page),pageSize);
		int total=postService.getPostTotalByPlateId(user.getId());
		int rowCount=0;
		if(total%pageSize!=0){
			rowCount = total / pageSize + 1; 
		}else{
			rowCount = total / pageSize; 
		}
		root.put("pageCount", rowCount);
		root.put("CurrentPage", page);
		root.put("list", posts);
		StringUtil.writeToWeb(JSONObject.fromObject(root).toString(), "html", response);

	}
	/**
	* @Title: getPersonCommentJson
	* @Description: TODO  
	* @return void  
	* @author 刘强   
	* @date 2015-5-12 下午3:26:10
	*/ 
	@RequestMapping(value="getPersonCommentJson.do")
	public void getPersonCommentJson(HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> root=new HashMap<String,Object>();
		String page=request.getParameter("page");//当前页
		String cookieValue=DESUtils.decode(CookieHandler.getCookieValue(request, DefaultElements.COOKIE_NAME));
		User user=userService.getUserByEmail(cookieValue);//获取当前用户
		int pageSize=Integer.parseInt(ConfigProperties.get("personCommentSize"));
		List<Comment> lists=commentService.getCommentByUserId(user.getId(), Integer.parseInt(page), pageSize);
		int total=commentService.getCommentTotalByUserId(user.getId());
		int rowCount=0;
		if(total%pageSize!=0){
			rowCount = total / pageSize + 1; 
		}else{
			rowCount = total / pageSize; 
		}
		root.put("pageCount", rowCount);
		root.put("CurrentPage", page);
		root.put("list", lists);
		StringUtil.writeToWeb(JSONObject.fromObject(root).toString(), "html", response);

	}
	
}
